﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using HostServicePhoneCommands.Properties;
using InterfacesPhoneCommands;

namespace HostServicePhoneCommands
{
    public partial class SysTrayApp : Form
    {

        private bool _flagActionDeviceSelect;
        private bool _flagActionRefreshMachine;

        private Thread _threadUpdateVms;
        private Thread _threadConnectDevice;
        private readonly Thread _threadStatus;
        private readonly ManualResetEvent _endThreadStatus;
        private readonly ConnectableDevice[] _devices;

        private VirtualMachine[] _virtualMachines;

        public SysTrayApp()
        {
            InitializeComponent();

            if (!Program.DebugMode)
            {
                OpenConsoleDebugtoolStripMenuItem.Visible = false;
                closeConsoleDebugToolStripMenuItem.Visible = false;
            }
            else
            {
                OpenConsoleDebugtoolStripMenuItem.Visible = true;
                closeConsoleDebugToolStripMenuItem.Visible = false;
            }

            emulatorstoolStripMenuItem.DropDown.Closing += EmulatorstoolStripMenuItemClosing;
            virtualMachinesToolStripMenuItem.DropDown.Closing += VirtualMachinesToolStripClosing;

            SysAppNotifyIcon.Text = Resources.TitleTray;
            closeEmulatorToolStripMenuItem.Checked = Settings.Default.CloseEmulator;
            _devices = Program.PhoneService.ConnectableDevice().Value;
            if (Settings.Default.CloseEmulator)
            {
                foreach (var closedev in _devices.Where(d => d.IsEmulator))
                {
                    Program.PhoneService.CloseEmulator(closedev.Name);
                }
            }
            if (_devices.Any())
            {
                ConnectableDevice defDevice = null;
                if (!string.IsNullOrEmpty(Settings.Default.LastDevice))
                {
                    defDevice = _devices.FirstOrDefault(d => d.Name == Settings.Default.LastDevice);
                }
                if (defDevice == null)
                {
                    defDevice = _devices.FirstOrDefault(d => d.IsEmulator && !d.IsLegacyEmulator);
                }
                if (defDevice != null)
                {
                    statusToolStripMenuItem.Text = defDevice.Name;
                    foreach (var item in _devices.Select(device =>
                        new ToolStripMenuItem
                            {
                                Text = device.Name,
                                Checked = (device.Name == defDevice.Name)
                            }))
                    {
                        item.Click += DeviceSelectedClick;
                        item.MouseDown += DeviceSelectedMouseDown;

                        emulatorstoolStripMenuItem.DropDownItems.Add(item);
                    }
                    emulatorstoolStripMenuItem.Text = string.Format(Resources.EmulatorsMenu, _devices.Count(d => d.IsEmulator));
                    Program.PhoneService.SelectConnectableDevice(defDevice.Name);
                    Settings.Default.LastDevice = defDevice.Name;
                    Settings.Default.Save();
                }
                else
                {
                    emulatorstoolStripMenuItem.Text = string.Format(Resources.EmulatorsMenu, 0);
                    statusToolStripMenuItem.Text = Resources.DeviceNotSeleted;
                }
            }
            else
            {
                statusToolStripMenuItem.Text = Resources.DeviceNotSeleted;
                emulatorstoolStripMenuItem.Enabled = false;
            }

            SetStatusMenu();

            virtualMachinesToolStripMenuItem.Enabled = false;
            virtualMachinesToolStripMenuItem.Text = Resources.Processing;
            _threadUpdateVms = new Thread(ListenMachines);
            _threadUpdateVms.Start(false);

            _endThreadStatus = new ManualResetEvent(false);
            _threadStatus = new Thread(ListenStatus);
            _threadStatus.Start(null);

        }


        private void DeviceSelectedMouseDown(object sender, MouseEventArgs e)
        {
            _flagActionDeviceSelect = true;
        }

        private void EmulatorstoolStripMenuItemClosing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            if (_flagActionDeviceSelect)
            {
                _flagActionDeviceSelect = false;
                e.Cancel = true;
            }
        }

        private void StartThreadUpdateHyperVMachines(bool reload)
        {
            Invoke((MethodInvoker)delegate
            {
                virtualMachinesToolStripMenuItem.Enabled = false;
                virtualMachinesToolStripMenuItem.Text = Resources.Processing;
            });
            _threadUpdateVms = new Thread(ListenMachines);
            _threadUpdateVms.Start(reload);
        }

        private ToolStripMenuItem CreateMenuMachine(VirtualMachine machine)
        {
            var name = machine.Name.ToLower().Replace("." + Environment.UserName.ToLower(), "");
            var displayname = machine.Name.Substring(0, name.Length).Replace("Emulator ", "Hyper-V ");
            displayname += "(" + machine.State + ")";
            var item = new ToolStripMenuItem { Text = displayname, Tag = machine.Name };
            var isEnabled = false;
            switch (machine.State)
            {
                case VirtualMachineState.Enabled:
                    {
                        isEnabled = true;
                        item.Image = Resources.LUZVERD;
                    }
                    break;
                case VirtualMachineState.Suspended:
                case VirtualMachineState.Paused:
                case VirtualMachineState.Disabled:
                    item.Image = Resources.LUZVERM;
                    break;
                case VirtualMachineState.Unknown:
                case VirtualMachineState.Starting:
                case VirtualMachineState.Snapshotting:
                case VirtualMachineState.Saving:
                case VirtualMachineState.Stopping:
                case VirtualMachineState.Pausing:
                case VirtualMachineState.Resuming:
                    item.Image = Resources.LUZCINZ;
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
            if (isEnabled)
            {
                var subitemClose = new ToolStripMenuItem
                {
                    Text = Resources.MenuCloseMachine,
                    Image = Resources.disconnect,
                    Tag = item.Tag
                };
                subitemClose.Click += CloseHyperVMachine;
                item.DropDownItems.Add(subitemClose);
                item.DropDownItems.Add(new ToolStripSeparator());
            }
            if (isEnabled)
            {
                var subitemCreateSnapshot = new ToolStripMenuItem
                {
                    Text = Resources.CreateSnapshotMenu,
                    Image = Resources.Binary,
                    Tag = item.Tag
                };
                subitemCreateSnapshot.Click += CreateSnapshotHyperVMachine;
                item.DropDownItems.Add(subitemCreateSnapshot);
            }
            if (machine.Snapshots.Any())
            {
                var subitemDeleteSnapshot = new ToolStripMenuItem
                {
                    Text = Resources.DeleteSnapshotsMenu,
                    Image = Resources.remove,
                    Tag = item.Tag
                };
                subitemDeleteSnapshot.Click += DeleteSnapshotHyperVMachine;
                item.DropDownItems.Add(subitemDeleteSnapshot);
                item.DropDownItems.Add(new ToolStripSeparator());
                var itemset = Settings.Default.StartSnapshot.Cast<string>().FirstOrDefault(d => d.StartsWith(machine.Name + "|"));
                var itemdef = itemset ?? machine.Name + "|" + machine.Snapshots[0];
                var hascheck = false;
                foreach (var subitemNameSnapshot in machine.Snapshots.Select(snp => new ToolStripMenuItem { Text  = snp, Tag = item }))
                {
                    if (!hascheck)
                    {
                        hascheck = (machine.Name + "|" + subitemNameSnapshot.Text == itemdef);
                    }
                    subitemNameSnapshot.Checked = (machine.Name + "|" + subitemNameSnapshot.Text == itemdef);
                    subitemNameSnapshot.Click += NameSnapshotSelected;
                    item.DropDownItems.Add(subitemNameSnapshot);
                }
                if (itemset != null)
                {
                    Settings.Default.StartSnapshot.Remove(itemset);
                }
                if (hascheck)
                {
                    Settings.Default.StartSnapshot.Add(itemdef);
                }
            }
            return item;
        }

        private void UpdateMenuHyperVMachines()
        {
            ClearHyperVMachines();
            _virtualMachines = Program.PhoneService.Machines(false).Value;
            var qtd = 0;
            foreach (var machine in _virtualMachines)
            {
                qtd++;
                var item = CreateMenuMachine(machine);
                virtualMachinesToolStripMenuItem.DropDownItems.Add(item);
            }
            Settings.Default.Save();
            virtualMachinesToolStripMenuItem.Text = string.Format(Resources.TitleVms, qtd);
            virtualMachinesToolStripMenuItem.Enabled = qtd != 0;
            emulatorstoolStripMenuItem.Enabled = true;
            cleanUpAllMachinesToolStripMenuItem.Enabled = true;
        }

        private void NameSnapshotSelected(object sender, EventArgs e)
        {
            var parent = (ToolStripMenuItem)((ToolStripMenuItem)sender).Tag;
            foreach (var item in parent.DropDownItems)
            {
                if (item == sender)
                {
                    ((ToolStripMenuItem)item).Checked = true;
                    var itemset = Settings.Default.StartSnapshot.Cast<string>().FirstOrDefault(d => d.StartsWith(parent.Tag.ToString() + "|"));
                    if (itemset != null)
                    {
                        Settings.Default.StartSnapshot.Remove(itemset);
                    }
                    Settings.Default.StartSnapshot.Add(parent.Tag + "|" + ((ToolStripMenuItem)item).Text);
                    Settings.Default.Save();
                }
                else
                {
                    var itemMenu = item as ToolStripMenuItem;
                    if (itemMenu != null && itemMenu.Tag == parent)
                    {
                        ((ToolStripMenuItem)item).Checked = false;
                    }
                }
            }
        }

        private void CreateSnapshotHyperVMachine(object sender, EventArgs e)
        {
            //close any form 
            foreach (var ofrm in OwnedForms.Where(ofrm => !(ofrm is CreateSnapshotHyperV)))
            {
                ofrm.Close();
            }
            //find and active 
            foreach (var ofrm in OwnedForms.OfType<CreateSnapshotHyperV>())
            {
                ofrm.Activate();
                return;
            }
            var frm = new CreateSnapshotHyperV { NameMachine = ((ToolStripMenuItem)sender).Tag.ToString(), ShowInTaskbar = false };
            frm.Show(this);
        }

        private void DeleteSnapshotHyperVMachine(object sender, EventArgs e)
        {
            //close any form 
            foreach (var ofrm in OwnedForms.Where(ofrm => !(ofrm is DeleteSnapshotHyperV)))
            {
                ofrm.Close();
            }
            //find and active form 
            foreach (var ofrm in OwnedForms.OfType<DeleteSnapshotHyperV>())
            {
                ofrm.Activate();
                return;
            }
            var frm = new DeleteSnapshotHyperV { NameMachine = ((ToolStripMenuItem)sender).Tag.ToString(), ShowInTaskbar = false };
            frm.Show(this);
        }

        private void CloseHyperVMachine(object sender, EventArgs e)
        {
            var nameVm = ((ToolStripMenuItem)sender).Tag.ToString();
            var nameEmulator = nameVm.ToLower().Replace("." + Environment.UserName.ToLower(), "");
            nameEmulator = nameVm.Substring(0, nameEmulator.Length);
            Program.PhoneService.CloseEmulator(nameEmulator);
            Program.PhoneService.CloseMachine(nameVm);
            SetStatusMenu();
        }

        private void ClearHyperVMachines()
        {
            if (_virtualMachines != null &&  _virtualMachines.Any())
            {
                var itemremove = new List<ToolStripItem>();
                foreach (var machine in _virtualMachines)
                {
                    itemremove.AddRange(
                        virtualMachinesToolStripMenuItem.DropDownItems.Cast<object>()
                                                        .Select(item => new {item, itemM = item as ToolStripItem})
                                                        .Where(
                                                            @t =>
                                                            @t.itemM != null &&
                                                            @t.itemM.Tag != null &&
                                                            @t.itemM.Tag.ToString() == machine.Name)
                                                        .Select(@t => (ToolStripItem) @t.item));
                }
                foreach (var item in itemremove)
                {
                    virtualMachinesToolStripMenuItem.DropDownItems.Remove(item);
                }
            }
        }

        private void ListenStatus(object param)
        {
            while (!_endThreadStatus.WaitOne(300, false))
            {
                Invoke((MethodInvoker)delegate
                {
                    var cmd = Program.PhoneService.IsConnected();
                    if (cmd.Successful)
                    {
                        if (connectToolStripMenuItem.Enabled)
                        {
                            statusToolStripMenuItem.Text = cmd.ReturnValue;
                            SetStatusMenu(true);
                        }
                    }
                    else
                    {
                        if (!connectToolStripMenuItem.Enabled)
                        {
                            //close any form 
                            foreach (var ofrm in OwnedForms)
                            {
                                ofrm.Close();
                            }
                            SetStatusMenu(false);
                        }
                    }
                });
            }
        }

        private void DeviceSelectedClick(object sender, EventArgs e)
        {
            var reconnect = false;
            var cmd = Program.PhoneService.IsConnected();
            ConsoleUtil.AddLogDebug(string.Format(Resources.LogIsConnected, cmd.Successful));
            if (cmd.Successful)
            {
                var namedev = cmd.ReturnValue;
                if (namedev != ((ToolStripMenuItem)sender).Text)
                {
                    var result = MessageBox.Show(string.Format(Resources.QCloseDevice, namedev), Resources.NameApp, MessageBoxButtons.YesNo);
                    if (result == DialogResult.No)
                    {
                        return;
                    }
                    ConsoleUtil.AddLogDebug(string.Format(Resources.LogDisconnecting, namedev));
                    cmd = Program.PhoneService.Disconnect();
                    ConsoleUtil.AddLog(!cmd.Successful
                        ? new LoggingMessage
                                {
                                    Message = string.Format(Resources.LogDisconnectError, namedev, cmd.ErrorMessage),
                                    ShowDate = true,
                                    Type = LoggingType.Error
                                }
                        : new LoggingMessage
                                {
                                    Message = Resources.LogDisconnectOk,
                                    ShowDate = true,
                                    Type = LoggingType.Debug
                                });
                    reconnect = cmd.Successful;
                    if (Settings.Default.CloseEmulator)
                    {
                        Program.PhoneService.CloseEmulator(namedev);
                    }
                }
            }
            var newdevselect = ((ToolStripMenuItem)sender).Text;
            Settings.Default.LastDevice = newdevselect;
            Settings.Default.Save();
            statusToolStripMenuItem.Text = newdevselect;
            foreach (var item in emulatorstoolStripMenuItem.DropDownItems)
            {
                if (item == sender)
                {
                    ((ToolStripMenuItem)item).Checked = true;
                    var cmds = Program.PhoneService.SelectConnectableDevice(newdevselect);
                    ConsoleUtil.AddLog(cmds.Successful
                        ? new LoggingMessage
                                {
                                    Message = string.Format(Resources.LogCmdSelectConnectableDeviceOK, newdevselect),
                                    ShowDate = true,
                                    Type = LoggingType.Debug
                                }
                        : new LoggingMessage
                                {
                                    Message = string.Format(Resources.LogCmdSelectConnectableDeviceErr, newdevselect, cmd.ErrorMessage),
                                    ShowDate = true,
                                    Type = LoggingType.Error
                                });
                }
                else
                {
                    var itemM = item as ToolStripMenuItem;
                    if (itemM != null && itemM.Tag == null)
                    {
                        itemM.Checked = false;
                    }
                }

            }
            if (reconnect)
            {
                var result = Program.PhoneService.Connect();
                if (result.Successful)
                {
                    ConsoleUtil.AddLogDebug(string.Format(Resources.LogCmdConnectOK, result.ReturnValue));
                    if (!ConsoleUtil.ModeConsoneOn)
                        NotifyShowBallon(string.Format(Resources.DeviceConnected, result.ReturnValue), ToolTipIcon.Info);
                }
                else
                {
                    ConsoleUtil.AddLogError(string.Format(Resources.LogCmdConnectErr, newdevselect, result.ErrorMessage));
                    if (!ConsoleUtil.ModeConsoneOn)
                        NotifyShowBallon(string.Format(Resources.DeviceNotConnected, newdevselect, result.ErrorMessage), ToolTipIcon.Error);
                }

                SetStatusMenu();

                var reload = result.Successful;
                if (result.Successful)
                {
                    if (!Program.PhoneService.Device().Value[0].IsLegacyEmulator)
                    {
                        reload =
                            !Program.PhoneService.Machines(false)
                                    .Value.Any(m => m.Name.ToLower().StartsWith(result.ReturnValue.ToLower()));
                    }
                }
                if (reload)
                {
                    StartThreadUpdateHyperVMachines(true);
                }
            }
        }

        private void NotifyShowBallon(string message, ToolTipIcon icon)
        {
            SysAppNotifyIcon.ShowBalloonTip(100, Resources.NameApp, message, icon);
        }

        protected override void OnLoad(EventArgs e)
        {
            Visible = false; // Hide form window.
            ShowInTaskbar = false; // Remove from taskbar.
            base.OnLoad(e);
        }


        private void SetStatusMenu(bool? checkStatus = null)
        {
            var statusOn = !checkStatus.HasValue ? Program.PhoneService.IsConnected().Successful : checkStatus.Value;
            ConsoleUtil.AddLogDebug(string.Format(Resources.LogIsConnected, statusOn));
            statusToolStripMenuItem.Image = statusOn ? Resources.LUZVERD : Resources.LUZVERM;
            if (!_devices.Any())
            {
                statusToolStripMenuItem.Image = Resources.LUZCINZ;
                statusOn = false;
                connectToolStripMenuItem.Enabled = false;
                disconnectToolStripMenuItem.Enabled = false;
            }
            else
            {
                connectToolStripMenuItem.Enabled = !statusOn;
                disconnectToolStripMenuItem.Enabled = statusOn;
            }
            explorerToolStripMenuItem.Enabled = statusOn;
            deployApplicationToolStripMenuItem.Enabled = statusOn;
        }

        private void OnDisconnectPhone(object sender, EventArgs e)
        {
            var cmd = Program.PhoneService.IsConnected();
            ConsoleUtil.AddLogDebug(string.Format(Resources.LogIsConnected, cmd.Successful));
            if (cmd.Successful)
            {
                var namedev = cmd.ReturnValue;
                var result = Program.PhoneService.Disconnect();
                if (result.Successful)
                {
                    if (Settings.Default.CloseEmulator)
                    {
                        Program.PhoneService.CloseEmulator(namedev);
                    }
                    ConsoleUtil.AddLogDebug(string.Format(Resources.LogDisconnectOk));
                    if (!ConsoleUtil.ModeConsoneOn)
                        NotifyShowBallon(string.Format(Resources.DeviceDisconnected, namedev), ToolTipIcon.Info);
                }
                else
                {
                    ConsoleUtil.AddLogError(string.Format(Resources.LogDisconnectError, namedev, cmd.ErrorMessage));
                    if (!ConsoleUtil.ModeConsoneOn)
                        NotifyShowBallon(string.Format(Resources.DeviceNotDisconnected, namedev, result.ErrorMessage), ToolTipIcon.Error);
                }
            }

            SetStatusMenu();
        }

        private void OpenConnectPhone(object param)
        {
                var cmd = Program.PhoneService.IsConnected();
                ConsoleUtil.AddLogDebug(string.Format(Resources.LogIsConnected, cmd.Successful));
                if (!cmd.Successful)
                {
                    var result = Program.PhoneService.Connect();
                    if (result.Successful)
                    {
                        ConsoleUtil.AddLogDebug(string.Format(Resources.LogCmdConnectOK, result.ReturnValue));
                        if (!ConsoleUtil.ModeConsoneOn)
                            Invoke((MethodInvoker) (() =>
                                NotifyShowBallon(
                                    string.Format(Resources.DeviceConnected, result.ReturnValue),
                                    ToolTipIcon.Info)));
                    }
                    else
                    {
                        ConsoleUtil.AddLogError(string.Format(Resources.NoDeviceConnected, result.ErrorMessage));
                        if (!ConsoleUtil.ModeConsoneOn)
                            Invoke((MethodInvoker) (() =>
                                NotifyShowBallon(
                                    string.Format(Resources.NoDeviceConnected, result.ErrorMessage),
                                    ToolTipIcon.Error)));
                    }
                    var reload = result.Successful;
                    if (result.Successful)
                    {
                        if (!Program.PhoneService.Device().Value[0].IsLegacyEmulator)
                        {
                            reload =
                                !Program.PhoneService.Machines(false)
                                        .Value.Any(m => m.Name.ToLower().StartsWith(result.ReturnValue.ToLower()));
                        }
                    }
                    if (reload)
                    {
                        Invoke((MethodInvoker)delegate
                        {
                            virtualMachinesToolStripMenuItem.Enabled = false;
                            virtualMachinesToolStripMenuItem.Text = Resources.Processing;
                            ListenMachines(true);
                        });
                    }
                }
                Invoke((MethodInvoker)delegate
                {
                    emulatorstoolStripMenuItem.Text = string.Format(Resources.EmulatorsMenu, _devices.Count(d => d.IsEmulator));
                    emulatorstoolStripMenuItem.Enabled = true;
                    SetStatusMenu();
                });
        }


        private void OnConnectPhone(object sender, EventArgs e)
        {
            emulatorstoolStripMenuItem.Text = Resources.Processing;
            emulatorstoolStripMenuItem.Enabled = false;
            _threadConnectDevice = new Thread(OpenConnectPhone);
            _threadConnectDevice.Start(null);
        }

        private void OnExit(object sender, EventArgs e)
        {
            if (!Program.DebugMode)
            {
                SysAppContextMenuStrip.Close();
                return;
            }

            if (ConsoleUtil.ModeConsoneOn)
            {
                MessageBox.Show(Resources.CloseFistConsole);
                return;
            }
            Program.PhoneService.CloseXdeVirtualMachines();
            var cmd = Program.PhoneService.IsConnected();
            if (cmd.Successful)
            {
                var namedev = cmd.ReturnValue;
                Program.PhoneService.Disconnect();
                if (Settings.Default.CloseEmulator)
                {
                    Program.PhoneService.CloseEmulator(namedev);
                }
            }
            _threadStatus.DisableComObjectEagerCleanup();
            _threadStatus.Abort();
            Close();
        }

        private void OpenConsoleDebug(object sender, EventArgs e)
        {
            if (!ConsoleUtil.ModeConsoneOn)
            {
                ConsoleUtil.OpenConsole();
            }
            OpenConsoleDebugtoolStripMenuItem.Visible = !ConsoleUtil.ModeConsoneOn;
            closeConsoleDebugToolStripMenuItem.Visible = ConsoleUtil.ModeConsoneOn;
        }

        private void CloseConsoleDebug(object sender, EventArgs e)
        {
            if (ConsoleUtil.ModeConsoneOn)
            {
                ConsoleUtil.CloseConsole();
            }
            OpenConsoleDebugtoolStripMenuItem.Visible = !ConsoleUtil.ModeConsoneOn;
            closeConsoleDebugToolStripMenuItem.Visible = ConsoleUtil.ModeConsoneOn;
        }

        private void ShowFileExplorer(object sender, EventArgs e)
        {
            //close any form 
            foreach (var ofrm in OwnedForms.Where(ofrm => !(ofrm is FileExplorer)))
            {
                ofrm.Close();
            }
            //find and active 
            foreach (var ofrm in OwnedForms.OfType<FileExplorer>())
            {
                ofrm.Activate();
                return;
            }
            var frm = new FileExplorer { ShowInTaskbar = false };
            frm.Show(this);
        }

        private void OnCloseEmulatorSetting(object sender, EventArgs e)
        {
            Settings.Default.CloseEmulator = !((ToolStripMenuItem)sender).Checked;
            Settings.Default.Save();
            ((ToolStripMenuItem)sender).Checked = Settings.Default.CloseEmulator;
        }

        private void ListenMachines(object param)
        {
            var realod = false;
            if (param is bool)
            {
                realod = (bool)param;
            }
            Invoke((MethodInvoker)delegate
            {
                virtualMachinesToolStripMenuItem.Text = Resources.Loading;
                Program.PhoneService.Machines(realod);
                Program.PhoneService.ChangedMachineStatus += PhoneServiceChangedMachineStatus;
                UpdateMenuHyperVMachines();
            });
        }

        private void PhoneServiceChangedMachineStatus(object sender, ChangedMachineStatusEventArgs e)
        {
            if (_virtualMachines != null &&  _virtualMachines.Any(m => m.Name == e.StateMachine.Name))
            {
                var itemremove = new List<ToolStripItem>();
                itemremove.AddRange(
                    virtualMachinesToolStripMenuItem.DropDownItems.Cast<object>()
                                                    .Select(item => new {item, itemM = item as ToolStripItem})
                                                    .Where(
                                                        @t =>
                                                        @t.itemM != null &&
                                                        @t.itemM.Tag != null &&
                                                        @t.itemM.Tag.ToString() == e.StateMachine.Name)
                                                    .Select(@t => (ToolStripItem) @t.item));

                foreach (var item in itemremove)
                {
                    var item1 = item;
                    Invoke((MethodInvoker) (() => virtualMachinesToolStripMenuItem.DropDownItems.Remove(item1)));
                }
                Invoke((MethodInvoker)(() =>
                        virtualMachinesToolStripMenuItem.DropDownItems.Add(CreateMenuMachine(e.StateMachine))));
            }
        }

        private void OncleanUpAllMachines(object sender, EventArgs e)
        {
            virtualMachinesToolStripMenuItem.Text = Resources.Processing;
            var result = Program.PhoneService.CleanUpMachines();
            if (result.Successful)
            {
                ConsoleUtil.AddLogDebug(Resources.CleanUpOk);
                if (!ConsoleUtil.ModeConsoneOn)
                    NotifyShowBallon(Resources.CleanUpOk, ToolTipIcon.Info);
            }
            else
            {
                ConsoleUtil.AddLogError(string.Format(Resources.CleanUpNok,
                                                        result.ErrorMessage));
                if (!ConsoleUtil.ModeConsoneOn)
                    NotifyShowBallon(
                        string.Format(Resources.CleanUpNok, result.ErrorMessage),
                        ToolTipIcon.Error);
            }
            virtualMachinesToolStripMenuItem.Text = Resources.Loading;
            UpdateMenuHyperVMachines();
        }

        private void VirtualMachinesToolStripClosing(object sender, ToolStripDropDownClosingEventArgs e)
        {
            if (_flagActionRefreshMachine)
            {
                _flagActionRefreshMachine = false;
                e.Cancel = true;
            }
        }
        
    }
}
